﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace SharpSoft.WPF.Controls
{
    /// <summary>
    /// 可关闭的标签页
    /// </summary> 
    [TemplatePart(Name = "PART_CLOSE", Type = typeof(Button))]
    public class CloseableTabItem : TabItem
    {
        static CloseableTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CloseableTabItem), new FrameworkPropertyMetadata(typeof(CloseableTabItem)));
        }

        /// <summary>
        /// 是否允许关闭
        /// </summary>
        public bool CanClose
        {
            get { return (bool)GetValue(CanCloseProperty); }
            set { SetValue(CanCloseProperty, value); }
        }

        public static readonly DependencyProperty CanCloseProperty =
            DependencyProperty.Register("CanClose", typeof(bool), typeof(CloseableTabItem), new PropertyMetadata(true));


        /// <summary>
        /// 在标签页关闭后触发
        /// </summary>
        public event RoutedEventHandler Closed
        {
            add { AddHandler(ClosedEvent, value); }
            remove { RemoveHandler(ClosedEvent, value); }
        }

        public static readonly RoutedEvent ClosedEvent = EventManager.RegisterRoutedEvent(
        "Closed", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CloseableTabItem));

        protected virtual void OnClosed()
        {
            RoutedEventArgs args = new RoutedEventArgs();
            args.RoutedEvent = CloseableTabItem.ClosedEvent;
            this.RaiseEvent(args);
        }

        /// <summary>
        /// 在将要关闭标签页时触发,可以取消关闭  
        /// </summary>
        public event CancelEventHandler Closing;

        protected virtual bool OnClosing()
        {
            CancelEventArgs args = new CancelEventArgs();
            this.Closing?.Invoke(this, args);
            return args.Cancel;
        }


        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Button closebtn = this.GetTemplateChild("PART_CLOSE") as Button;
            if (closebtn != null)
            {
                closebtn.Click += Closebtn_Click;
            }
        }
        private void Closebtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        public void Close()
        {
            var cancel = this.OnClosing();
            if (!cancel)
            {
                this.OnClose();
            }
        }

        protected void OnClose()
        {
            if (this.Parent is TabControl tc)
            {
                if (tc.Items.Contains(this))
                {
                    tc.Items.Remove(this);
                    this.OnClosed();
                }
            }
        }

    }
}
